package top.luo.mycat.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * v2 输出静态资源
 *
 * @author luo
 * @date 2021-03-19 11:16
 */
public class Response {

    private OutputStream ous;

    public Response() {
    }

    public Response(OutputStream ous) {
        this.ous = ous;
    }

    public void output(String content) throws IOException {
        ous.write(content.getBytes());
    }

    /**
     * 根据 url 获取静态请求所需的静态资源，读取后由输出流输出
     *
     * @param path 静态资源路径
     */
    public void outputHtml(String path) throws IOException {
        // 获取静态资源的绝对路径
        String absolutePath = StaticResourceUtils.getAbsolutePath(path);
        File file = new File(absolutePath);
        if (file.exists() && file.isFile()) {
            // 读取静态资源 并 输出
            StaticResourceUtils.output(new FileInputStream(file), ous);
        } else {
            // 404
            output(HttpProtocolUtils.getHttpHeaderNotFound());
        }

    }

}
